package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.FileAdapter;
import flc.ast.bean.MyFileBean;
import flc.ast.databinding.ActivityFileManageBinding;
import flc.ast.utils.Content;
import flc.ast.utils.MyUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

public class FileManageActivity extends BaseAc<ActivityFileManageBinding> {

    private FileAdapter fileAdapter;
    private Dialog myRenameDialog;
    private EditText dialogRename;
    private String selPath = "";

    @Override
    protected int onCreate() {
        return R.layout.activity_file_manage;
    }

    @Override
    protected void initView() {
        mDataBinding.ivFileManageBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivFileCompress.setOnClickListener(this);
        mDataBinding.ivFileDecompression.setOnClickListener(this);

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        fileAdapter = new FileAdapter();
        mDataBinding.rvFileList.setAdapter(fileAdapter);
        fileAdapter.addChildClickViewIds(R.id.ivFileItemMore);
        fileAdapter.setOnItemClickListener(this);
        fileAdapter.setOnItemChildClickListener(this);

        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivFileCompress://文件压缩
                FileZipActivity.isZip = true;
                startActivity(FileZipActivity.class);
                break;
            case R.id.ivFileDecompression://文件解压
                FileZipActivity.isZip = false;
                startActivity(FileZipActivity.class);
                break;
            //重命名弹框
            case R.id.tvDialogRenameCancel://取消
                myRenameDialog.dismiss();
                break;
            case R.id.tvDialogRenameRight://确定
                renameFile();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (FileUtils.isFile(fileAdapter.getItem(position).getPath())) {
            gotoPreviewFile(fileAdapter.getItem(position).getPath(), fileAdapter.getItem(position).getUri());
        } else {

        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivFileItemMore://更多
                showMore(view, fileAdapter.getItem(position));
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        getZipRecord();
    }

    //获取压缩记录
    private void getZipRecord() {
        RxUtil.create(new RxUtil.Callback<List<MyFileBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MyFileBean>> emitter) {
                List<MyFileBean> list = new ArrayList<>();
                String path = PathUtils.getFilesPathExternalFirst() + Content.MyZip;
                List<File> files = FileUtils.listFilesInDir(path);
                if (files.size() > 0) {
                    for (File file : files) {
                        list.add(new MyFileBean(file.getPath(), UriUtils.file2Uri(file).toString(), file.getName(), MyUtils.getFileSize(file)));
                    }
                }
                emitter.onNext(list);
            }

            @Override
            public void accept(List<MyFileBean> list) {
                getUnZipRecord(list);
            }
        });
    }

    //获取解压记录
    private void getUnZipRecord(List<MyFileBean> listZip) {
        RxUtil.create(new RxUtil.Callback<List<MyFileBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MyFileBean>> emitter) {
                List<MyFileBean> list = new ArrayList<>();
                String path = PathUtils.getFilesPathExternalFirst() + Content.MyUnZip;
                List<File> files = FileUtils.listFilesInDir(path);
                if (files.size() > 0) {
                    for (File file : files) {
                        list.add(new MyFileBean(file.getPath(), UriUtils.file2Uri(file).toString(), file.getName(), MyUtils.getFileSize(file)));
                    }
                }
                emitter.onNext(list);
            }

            @Override
            public void accept(List<MyFileBean> list) {
                if (listZip.size() > 0 || list.size() > 0) {
                    list.addAll(listZip);
                    fileAdapter.setList(list);
                    mDataBinding.rvFileList.setVisibility(View.VISIBLE);
                    mDataBinding.tvFileManageNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvFileList.setVisibility(View.GONE);
                    mDataBinding.tvFileManageNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //更多弹框
    private void showMore(View view, MyFileBean bean) {
        new XPopup.Builder(this)
                .hasShadowBg(false)
                .atView(view)
                .asCustom(new AttachPopupView(mContext) {

                    @Override
                    protected int getImplLayoutId() {
                        return R.layout.dialog_xpopup;
                    }

                    @Override
                    protected void onCreate() {
                        super.onCreate();
                        findViewById(R.id.tvDialogXpopupShare).setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dismiss();
                                shareFile(Uri.parse(bean.getUri()));
                            }
                        });
                        findViewById(R.id.tvDialogXpopupDelete).setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dismiss();
                                deleteFileData(bean.getPath());
                            }
                        });
                        findViewById(R.id.tvDialogXpopupRename).setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dismiss();
                                selPath = bean.getPath();
                                dialogRename.setText(FileUtils.getFileNameNoExtension(bean.getPath()));
                                myRenameDialog.show();
                            }
                        });
                    }
                })
                .show();
    }

    //分享文件
    private void shareFile(Uri uri) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(intent, "Share"));
    }

    //删除文件
    private void deleteFileData(String path) {
        showDialog(getString(R.string.delete_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                FileUtils.delete(path);
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        getZipRecord();
                    }
                }, 500);
            }
        });
    }

    //重命名文件
    private void renameFile() {
        String newName = dialogRename.getText().toString();
        if (TextUtils.isEmpty(newName)) {
            ToastUtils.showShort(R.string.please_input_file_name);
            return;
        }
        myRenameDialog.dismiss();
        showDialog(getString(R.string.rename_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                if (FileUtils.isFile(selPath)) {
                    String suffix = FileUtils.getFileExtension(selPath);
                    FileUtils.rename(selPath, newName + "." + suffix);
                } else {
                    FileUtils.rename(selPath, newName);
                }
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dismissDialog();
                        getZipRecord();
                    }
                }, 1000);
            }
        });
    }

    //跳转到预览文档应用
    private void gotoPreviewFile(String selPath, String selUri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType(getType(selPath)); // 设置要打开的文档类型
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            // 设备上至少安装了一个支持打开PDF文档的应用程序
            Uri uri = Uri.parse(selUri);
            Intent intent2 = new Intent(Intent.ACTION_VIEW);
            intent2.setData(uri);
            startActivity(intent2);
        } else {
            // 设备上没有安装任何支持打开PDF文档的应用程序
            ToastUtils.showShort(R.string.no_preview_app);
        }
    }

    //获取对应的type
    private String getType(String path) {
        String suffix = FileUtils.getFileExtension(path);
        String type = "";
        if (suffix.equalsIgnoreCase("pdf")) {
            type = "application/pdf";
        } else if (suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx")) {
            type = "application/ppt";
        } else if (suffix.equalsIgnoreCase("txt")) {
            type = "application/txt";
        } else if (suffix.equalsIgnoreCase("doc") || suffix.equalsIgnoreCase("docx")) {
            type = "application/doc";
        } else if (suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx")) {
            type = "application/xls";
        } else if (suffix.equalsIgnoreCase("zip")) {
            type = "application/zip";
        } else if (suffix.equalsIgnoreCase("rar")) {
            type = "application/rar";
        }
        return type;
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialogRename = inflate.findViewById(R.id.etDialogRename);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView right = inflate.findViewById(R.id.tvDialogRenameRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}